package vn.vfriends.vcms.admin.servlet;

import eu.medsea.mimeutil.MimeUtil2;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLDecoder;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author tuan@vfriends.vn
 */
@WebServlet(name = "fileDownloadServlet", urlPatterns = {"/file"})
public class FileDownloadServlet extends HttpServlet {
    
    static private final Logger logger = LoggerFactory.getLogger(FileDownloadServlet.class);
    
    static final long serialVersionUID = 1L;
    
    private static final int BUFSIZE = 4096;
    
    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        if(!StringUtils.isEmpty(request.getParameter("p"))) {
            String path = URLDecoder.decode(request.getParameter("p"), "UTF-8");
            try {
                String rootPath = this.getServletContext().getInitParameter("ROOT_PATH");
                File file = new File(FilenameUtils.concat(rootPath, path));
                String mimetype = this.getMimeType(file);
                if (mimetype == null) {
                    mimetype = "application/octet-stream";
                }
                response.setContentType(mimetype);
                response.setContentLength((int)file.length());
                if(mimetype.indexOf("image") >= 0) {
                    response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\"");
                } else {
                    response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
                }
                
                byte[] byteBuffer = new byte[BUFSIZE];
                DataInputStream in = new DataInputStream(new FileInputStream(file));

                // reads the file's bytes and writes them to the response stream
                int length   = 0;
                ServletOutputStream outStream = response.getOutputStream();
                while ((in != null) && ((length = in.read(byteBuffer)) != -1)) {
                    outStream.write(byteBuffer, 0, length);
                }

                in.close();
                outStream.flush();
                outStream.close();
            } catch (Exception e) {
                logger.error(e.getMessage());
            }
        } else {
            logger.info("Parameter is empty.");
        }
    }
    
    private String getMimeType(File file) {
        MimeUtil2 mimeUtil = new MimeUtil2();
        mimeUtil.registerMimeDetector("eu.medsea.mimeutil.detector.MagicMimeMimeDetector");
        return MimeUtil2.getMostSpecificMimeType(mimeUtil.getMimeTypes(file)).toString();
    }
}
